<template>
	<view @click="isMore = false">
		<view class="goods-head" :style="'background:rgba(255,255,255,' + PageScrollTop / 100 + ')'">
			<!-- 返回 -->
			<view class="back" @click="onBack">
				<view class="back-one" :class="{ action: PageScrollTop > 120 }">
					<text></text>
				</view>
			</view>

		</view>

		<!-- banner，标题 -->


		<view class="banner-title">

			<!-- banner -->
			<view class="banner">
				<swiper class="screen-swiper round-dot" indicator-dots="true" circular="true" autoplay="true"
					interval="5000" duration="500">
					<swiper-item v-for="(item, index) in goodsInfo.img_list" :key="index">
						<image :src="item" mode="aspectFill"></image>
					</swiper-item>
				</swiper>
			</view>
			<!-- 价格 -->
			<view class="goods-title">
				<text>{{goodsInfo.title}}</text>
			</view>
			<view class="price-info">
				<view class="price">
					<text class="min">当前竞拍价：</text>
					<text class="max">￥{{now_price}}</text>
				</view>

			</view>
			<view class="goods-title">
				<text>竞拍剩余时间：{{countTime}}</text>
			</view>
			<view class="goods-title">
				<text>本轮竞拍剩余时间：{{allcountTime}}</text>
			</view>
			<view class="price-info">
				<view class="price">
					<text class="min">起拍价：</text>
					<text>￥{{goodsInfo.start_price}}</text>
				</view>
				<view class="price">
					<text class="min">加价幅度：</text>
					<text>￥{{goodsInfo.add_price}}</text>
				</view>
			</view>


		</view>

		<!-- 属性 -->
		<view class="shuxing">
			<view class="shuxing-list">
				<view class="title">
					商品参数
				</view>
				<view class="list" v-for="(el,idx) in goodsInfo.attribute" :key="idx">
					<view class="weight">
						{{el._key}}:
					</view>
					<view class="canshu">
						{{el._value}}
					</view>
				</view>
			</view>
			<view class="xiangqing">
				<view class="title">
					快递费
				</view>
				<text>{{goodsInfo.express_fee||'免邮'}}</text>
			</view>
			<view class="xiangqing">
				<view class="title">
					可否自提
				</view>
				<text>{{goodsInfo.is_self_pickup | is_self_pickupFn}}</text>
			</view>
			<view class="xiangqing">
				<view class="title">
					详情介绍
				</view>
				<text>{{goodsInfo.introduce}}</text>
			</view>

		</view>

		<view class="page-footer">
			<view class="footer-buy">

				<view class="buy-at">
					<text @click="sendMessage">立即竞价</text>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	import GoodsAttr from '../../components/GoodsAttr/GoodsAttr.vue';
	import {
		getNowGoods,
		savePaySort,
		delNameById,
		getLSpaySort
	} from '@/config/api.js';
	export default {
		filters: {
			is_self_pickupFn(s) {
				if (s == 1) return '是';
				return '不可'
			}
		},
		components: {},
		data() {
			return {
				now_price: 0,
				goodsInfo: {},
				countTime: 0,
				allcountTime: 0,
				orderInfo: {},
				socketOpen: false,
				socketTask: null,
				user_id: null,
			};
		},
		onLoad(options) {
			this.connectSocket();
			// this.getNowGoodsInfo();
			this.user_id = uni.getStorageSync('userInfo')['id'];
		},
		onUnload() {
			if (this.socketTask) {
				this.socketTask.close(); // 关闭连接
				this.socketTask = null; // 清空对象
				this.socketOpen = false;
			}
		},
		onPageScroll(e) {},
		methods: {
			onBack() {
				uni.navigateBack();
			},
			goodsInfo(data) {
				console.log(data)
			},
			getNowAcc(){
				let num = 0;
				if(!this.now_price){
					num = this.goodsInfo.start_price;
				}else{
					num = this.goodsInfo.add_price; 
				}
				return num
			},
			receivedmessage(data) {
				const __ = {
					goodsInfo: (res) => {
						if (!res || !res.data) return;
						res.data['img_list'] = res.data['img_list'].split(',');
						this.goodsInfo = res.data;
						this.orderInfo = res.orderInfo;
						this.now_price = res.orderInfo.now_price
					},
					fetchPrice: (data) => {
						uni.$u.toast('竞拍加价成功！   ')
						this.now_price = data.price;
					},
					fetchData: (data) => {
						console.log(data, typeof data)
						this.countTime = data.t1;
						this.allcountTime = data.t2;
					},
					endTimefn: (data) => {
						console.log(data, typeof data)
						uni.$u.toast(data.mes)
					}
				}

				// const goodsInfo = (data)=>{
				// 	console.log(data)
				// }
				__[data.event] && __[data.event](data.data)
			},
			connectSocket() {
				const _this = this;
				// const socketUrl = 'ws://192.168.1.5:8360/ws';
				
				const socketUrl = 'wss://www.daoyikeji.com/ws';
				this.socketTask = uni.connectSocket({
					url: socketUrl,
					header: {
						'content-type': 'application/json',
						'x-zyt-token': uni.getStorageSync('token')
					},
					success: () => {
						console.log('WebSocket connection created');
					},
				});
				this.socketTask.onOpen(() => {
					console.log('WebSocket opened');
					this.socketOpen = true;
				});
				this.socketTask.onMessage((message) => {
					const data = JSON.parse(message.data);
					// console.log(data.event,_this[data.event])
					// _this[data.event](data.data);
					this.receivedmessage(data);
					// console.log('Received message from server:', message.data);
				});

				this.socketTask.onClose(() => {
					console.log('WebSocket closed');
					this.socketOpen = false;
				});
				this.socketTask.onError((error) => {
					console.error('WebSocket error:', error);
				});
			},
			
			sendMessage() {
				if (!this.user_id) return uni.$u.toast('请先登录！');
				if (this.countTime <= 2) return uni.$u.toast('拍品已锁单！');
				const _this = this;
				if (this.socketOpen) {
					const message = 'Hello from UniApp';
					getLSpaySort({
						type: 4,
						acc: _this.getNowAcc()
					}).then(data => {
						if(data.signType){
							wx.requestPayment({
							  timeStamp: data.timeStamp,
							  nonceStr: data.nonceStr,
							  package: data.package,
							  signType: data.signType,
							  paySign: data.paySign,
							  success (res) { 
								 _this.socketTask.send({
								 	data: JSON.stringify({
								 		event: 'message',
								 		data: {
								 			user_id: _this.user_id,
								 			order_id: _this.orderInfo.id
								 		}
								 	}),
								 	success: () => {
								 		console.log('Message sent:', message);
								 	},
								 	fail: (error) => {
								 		console.error('Failed to send message:', error);
								 	},
								 });
							  },
							  fail (res) { 
								  // 支付失败 删除商品
								  delNameById({order_sn: data._order_sn})
							  }
							})
						}
					})
					
				} else {
					return uni.$u.toast('链接已断开请尝试重新加载此页面！');
				}
			},
			closeSocket() {
				if (this.socketOpen) {
					this.socketTask.close({
						success: () => {
							console.log('WebSocket closed');
						},
					});
				}
			},

			getNowGoodsInfo() {
				getNowGoods().then(res => {
					this.goodsInfo = res.data;
					this.orderInfo = res.orderInfo;
					this.now_price = res.orderInfo.now_price;
				})
			},
			onBack() {

				uni.navigateBack();
			}
		}
	};
</script>

<style scoped lang="scss">
	@import 'GoodsDetails.scss';
</style>